<template>
  <el-form
    label-width="120px"
    :model="spuInfo"
    ref="ruleFormRef"
    :rules="rules"
  >
    <el-form-item label="SPU名称" prop="spuName">
      <el-input
        placeholder="请输入SPU名称"
        v-model="spuInfo.spuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="品牌" prop="tmId">
      <el-select placeholder="请选择" v-model="spuInfo.tmId">
        <el-option
          :label="tr.tmName"
          v-for="tr in TradmarkSpuList"
          :key="tr.id"
          :value="tr.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述" prop="description">
      <el-input
        v-model="spuInfo.description"
        :rows="4"
        type="textarea"
        placeholder="SPU描述"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU图片" prop="spuImageList">
      <el-upload
        :action="`${BASE_URL}/admin/product/upload`"
        v-model:file-list="fileList"
        list-type="picture-card"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :on-remove="handleRemove"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>
    <el-form-item label="销售属性" prop="spuSaleAttr">
      <el-select
        v-model="spuInfo.spuSaleAttr"
        :placeholder="`还剩下${filterSpuSaleAttrList.length}未选择`"
      >
        <el-option
          :label="sst.name"
          v-for="sst in filterSpuSaleAttrList"
          :key="sst.id"
          :value="sst.name"
        ></el-option>
      </el-select>
      <el-button
        type="primary"
        :disabled="!spuInfo.spuSaleAttr"
        @click="addSaleAtt"
        >添加销售属性</el-button
      >
    </el-form-item>
    <el-form-item prop="spuSaleAttrList">
      <el-table :data="spuInfo.spuSaleAttrList" border style="width: 100%">
        <el-table-column align="center" type="index" label="序号" width="180" />
        <el-table-column prop="saleAttrName" label="属性名" width="180" />
        <el-table-column label="属性值名称列表" v-slot="{ row }">
          <!-- <template v-slot="{}"> -->
          <el-tag
            v-for="tag in row.spuSaleAttrValueList"
            :key="tag.saleAttrValueName"
            class="mx-1"
            closable
            :disable-transitions="false"
            @close="handleClose(tag, row)"
          >
            {{ tag.saleAttrValueName }}
          </el-tag>
          <el-input
            v-if="row.inputVisible"
            ref="InputRef"
            v-model="inputValue"
            class="ml-1 w-20"
            size="small"
            @keyup.enter="handleInputConfirm(row)"
            @blur="handleInputConfirm(row)"
            style="width: 80px"
          />
          <el-button
            v-else
            class="button-new-tag ml-1"
            size="small"
            @click="showInput(row)"
          >
            + New Tag
          </el-button>
          <!-- </template> -->
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template v-slot="$index">
            <el-popconfirm
              width="220"
              confirm-button-text="OK"
              cancel-button-text="No, Thanks"
              :icon="InfoFilled"
              icon-color="#626AEF"
              title="你确定要删除吗?"
              @confirm="confirmEvent($index)"
            >
              <template #reference>
                <el-button :icon="Delete" type="danger"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
        >保存</el-button
      >
      <el-button @click="resetForm(ruleFormRef)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang='ts'>
export default {
  name: "SpuForm",
};
</script>
<script lang='ts' setup>
import { Plus, Delete, InfoFilled } from "@element-plus/icons-vue";
import { computed, onMounted, reactive, ref, nextTick } from "vue";
import { ElMessage, ElInput } from "element-plus";
import {
  reqGetSpuAttrData,
  reqGetBaseSaleAttrListData,
  reqGetSaveSpuData,
  reqGetSpuImageListData,
  reqGetSpuSaleAttrListData,
  updataSpuAllData,
} from "@/api/product/spu";
import type {
  UploadProps,
  UploadUserFile,
  FormInstance,
  FormRules,
} from "element-plus";
import { typeSpu } from "../type";
import { useCategoryListStore } from "@/stores/categoryList";
const categoryStore = useCategoryListStore();
// 上传图片
const imageUrl = ref("");
const fileList = ref<UploadUserFile[]>([]);
//上传地址，会从env.development中加载
const BASE_URL = import.meta.env.VITE_API_URL;
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

// 定义数据存储品牌数据列表和销售属性列表,请求的数据
const TradmarkSpuList = ref([]);
const baseSaleAttrList = ref([]);
//定义一个存储spu相关数据的变量（发送请求的变量）
const spuInfo = reactive({
  spuName: "", //SPU名称
  tmId: "", // spu品牌
  description: "", // spu描述
  spuImageList: [], // 存储spu图片的数组
  spuSaleAttrList: [], // 属性名列表项
  category3Id: "", // 三级id
  spuSaleAttr: "", // 收集选中的属性，销售属性输入框
  ...props.currentSpuInfo,
});

// Tag标签
const inputValue = ref("");
const dynamicTags = ref(["Tag 1", "Tag 2", "Tag 3"]);
const inputVisible = ref(false); //定义一个属性来控制标签的展示，各个标签互不影响
const InputRef = ref<InstanceType<typeof ElInput>>();

// 父组件传递的参数
const emit = defineEmits(["setshowSpu"]);
const props = defineProps(["currentSpuInfo"]);
// 校验
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  spuName: [
    { required: true, message: "请输入SPU名称", trigger: "blur" },
    { min: 3, max: 5, message: "长度在 3 to 5", trigger: "blur" },
  ],
  tmId: [{ required: true, message: "请选择品牌名称", trigger: "change" }],
  description: [{ required: true, message: "请填写描述", trigger: "blur" }],
  spuImageList: [
    {
      type: "array",
      required: true,
      message: "请至少上传一张图片",
      trigger: "blur",
    },
  ],
  spuSaleAttrList: [
    {
      type: "array",
      required: true,
      message: "请选择销售属性",
      trigger: "blur",
    },
  ],
  // category3Id: [
  //   { required: true, message: 'Please input Activity name', trigger: 'blur' },
  // ],
  // spuSaleAttr:[
  //   { required: true, message: 'Please input Activity name', trigger: 'blur' },
  // ],
});

// 1.请求品牌数据和销售属性数据，页面渲染完成就应该请求，生命周期钩子函数
onMounted(async () => {
  // promise.all的结果只有全部成功才返回成功，并且返回的数据，严格按照书写顺写
  // 一次性发送两个或者四个请求，合并数组
  const { id } = spuInfo;
  // 品牌和属性请求
  let promises = [reqGetSpuAttrData(), reqGetBaseSaleAttrListData()];
  //  图片列表和属性、属性值列表
  if (id) {
    promises = promises.concat([
      reqGetSpuImageListData(id),
      reqGetSpuSaleAttrListData(id),
    ]);
  }
  try {
    const [
      getSpuListData,
      getSpuSaleAttrData,
      getSpuIamgeData,
      getSpuAttrData,
    ] = await Promise.all(promises);
    TradmarkSpuList.value = getSpuListData;
    baseSaleAttrList.value = getSpuSaleAttrData;
    // console.log("rr", getSpuIamgeData, getSpuAttrData);
    // console.log(TradmarkSpuList);
    // console.log(SpuSaleAttrList);
    if (getSpuIamgeData && getSpuAttrData) {
      fileList.value = getSpuIamgeData.map((item) => {
        return {
          name: item.imgName,
          url:  item.imgUrl,
        };
      });
      spuInfo.spuSaleAttrList = getSpuAttrData;
      spuInfo.spuImageList = getSpuIamgeData
    }
  } catch {
    ElMessage("数据请示失败了");
  }
});

//2.图片上传成功
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  console.log(response, uploadFile);
  spuInfo.spuImageList.push({
    imgName: uploadFile.name,
    imgUrl: response.data,
  });
  //手动清空校验
  ruleFormRef?.value?.clearValidate();
};

// 3.图片上传前的校验
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const fileType = ["image/jpeg", "image/webp"];
  if (!fileType.includes(rawFile.type)) {
    ElMessage.error("图片格式不正确请重新上传");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过2MB!");
    return false;
  }
  return true;
};

//4.删除图片成功后的操作，需要重新显示剩余的图片
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  //删除的图片，剩余的图片数组
   console.log(uploadFile, uploadFiles) 
  spuInfo.spuImageList = uploadFiles.map((item) => {
    return {
      imgName: item.name,
      imgUrl: item.response ? item.response.data :item.url,
    };
  });
};
// 5.添加销售属性
const addSaleAtt = () => {
  // 5.1-----------当销售属性值那一行有值并且属性值不为空的时候不能点击添加属性按钮，需要做判断
  const spuSaleList = spuInfo.spuSaleAttrList;
  if (
    spuSaleList.length != 0 &&
    spuSaleList.some((item) => item.spuSaleAttrValueList == "")
  ) {
    ElMessage("存在属性为空的情况，请继续填写");
    return;
  }
  // 5.2在数组增加新的属性
  const id = baseSaleAttrList.value.find(
    (item) => item.name === spuInfo.spuSaleAttr
  ).id;
  spuInfo.spuSaleAttrList.push({
    // inputVisible: false,
    saleAttrName: spuInfo.spuSaleAttr,
    spuSaleAttrValueList: [],
    baseSaleAttrId: id,
  });
  // 清空，改变了数组的长度，使得输入框的提示信息数量实时变化（会影响后面添加属性值id）
  spuInfo.spuSaleAttr = "";
};
// 6.使用计算属性，获取剩余的未选择销售属性
const filterSpuSaleAttrList = computed(() => {
  return baseSaleAttrList.value.filter((item) => {
    // 属性下拉框列表和属性表格的name作比较，排除相等的剩下的是要显示的
    return !spuInfo.spuSaleAttrList.find((i) => item.name === i.saleAttrName);
  });
});

// 7.删除销售属性值
const confirmEvent = (index) => {
  spuInfo.spuSaleAttrList.splice(index, 1);
};

//8.tag标签
// 8.1选择展示
const showInput = (row) => {
  // inputVisible.value = true
  row.inputVisible = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};
//8.2 失去焦点确认添加新的属性值
const handleInputConfirm = (row) => {
  // --------------属性值的名称不能重复，做判断
  //  const spuSaleList = spuInfo.spuSaleAttrList
  // if(spuSaleList.length !=0 && spuSaleList.spuSaleAttrValueList.some(item => item.saleAttrValueName == inputValue.value )){
  //   row.inputVisible = false
  //   inputValue.value = ''
  //   return ElMessage('属性值重复，请输入')
  // }
  const spuSaleList = row.spuSaleAttrValueList;
  if (
    spuSaleList.length != 0 &&
    spuSaleList.some((item) => item.saleAttrValueName == inputValue.value)
  ) {
    row.inputVisible = false;
    inputValue.value = "";
    return ElMessage("属性值重复，请重新输入");
  }
  if (inputValue.value) {
    row.spuSaleAttrValueList.push({
      saleAttrValueName: inputValue.value,
      saleAttrName: row.saleAttrName,
      // ----------添加id
      baseSaleAttrId: row.baseSaleAttrId,
    });
  }
  // inputVisible.value = false
  row.inputVisible = false;
  inputValue.value = "";
};
//8.3 关闭,删除单个tag标签（属性值）
const handleClose = (tag: string, row) => {
  // dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
  row.spuSaleAttrValueList.splice(row.spuSaleAttrValueList.indexOf(tag), 1);
};

//9.提交表单,增加spu数据
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 对于销售属性中属性值，提交之前一定要校验一下
      const spuSaleAttrCheck = spuInfo.spuSaleAttrList;
      if (
        spuSaleAttrCheck.length &&
        spuSaleAttrCheck.some((item) => item.spuSaleAttrValueList.length === 0)
      ) {
        console.log(111);
        ElMessage.warning("有属性的属性值为空,请添加...");
      }
      spuInfo.category3Id = categoryStore.category3Id;
      console.log(spuInfo.id);
      if(spuInfo.id){
        await updataSpuAllData(spuInfo)
      }else{
        await reqGetSaveSpuData(spuInfo);
      }
      ElMessage.success("操作数据成功");
      // 要跳转到spu列表页面
      emit('setshowSpu',typeSpu.SPU_LIST)
    } else {
      console.log("error submit!", fields);
    }
  });
};
//10.取消表单
// const resetForm = (formEl: FormInstance | undefined) => {
//   if (!formEl) return
//   formEl.resetFields()
// }
const resetForm = () => {
  emit("setshowSpu", typeSpu.SPU_LIST);
  // spuInfo.value ={}
  console.log(spuInfo);
};
</script>

<style scoped>
</style>

<style>
</style>